import router from './router/index'
import { useStore } from './store/index'
import { storeToRefs } from 'pinia'
import NProgress from "nprogress";
import "nprogress/nprogress.css";
NProgress.configure({ showSpinner: false });

const modules = import.meta.glob("./views/**/**.vue");
//白名单
const noLimitPages = [
    { path: "/index", title:"智慧社区", component: "home/homeindex.vue" },
    { path: "/newsadd", title:"添加新闻", component: "news/newsAdd.vue" },
    { path: "/stroesadd", title:"添加门店", component: "stores/storesAdd.vue" },
]
router.beforeEach((to,from)=>{
    NProgress.start();
    if (to.path==='/login') {
        return
    }
    const store = useStore()
    let {token,menus } = storeToRefs(store)
    if (token.value=="" ) {
        return '/login'
    }
    else{
        if (router.getRoutes().length===3) {
            noLimitPages.forEach(item=>{
                router.addRoute('Home',{
                    path:item.path,
                    name:item.path,
                    component:modules[`./views/${item.component}`]
                })
            })
            let _menus = menus.value.filter((item:any)=>item.url)
       
            _menus.forEach((item:any)=>{
               
                let url = item.url.replace('/','')
                let component = modules[`./views/${url}/${url}.vue`];
                if (!component) component = modules[`./views/404.vue`];
                router.addRoute('Home',{
                    path:item.url,
                    name:url,
                    component,
                })
            })
            return to.fullPath
         }
    }

})

router.afterEach((to:any)=>{
    document.title=to.meta.title ?? "智慧社区";
    NProgress.done();
})